package org.martin.snsrs.daos;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.martin.snsrs.beans.ActivityTags;
import org.martin.snsrs.beans.Tags;
import org.martin.snsrs.beans.UserTag;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class TagsDao {
	private HibernateTemplate hibernateTemplate;
	
	private SessionFactory sessionFactory;
	
	private Session session;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		session = sessionFactory.openSession();
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}
	
	public List<Tags> getUserTags(Integer userID){
		Criteria criteria = session.createCriteria(UserTag.class);
		criteria.add(Restrictions.eq("userID", userID));
		criteria.setFetchMode("Tags", FetchMode.JOIN);
		List<UserTag> userTags = criteria.list();
		List<Tags> tags = new ArrayList<Tags>();
		for(UserTag tag : userTags){
			tags.add(tag.getTag());
		}
		return tags;
	}
	
	public void saveNewTags(List<Tags> tags){
		for(Tags tag : tags){
			Criteria criteria = session.createCriteria(Tags.class);
			criteria.add(Restrictions.eq("tagName", tag.getTagName()));
			List<Tags> list = criteria.list(); 
			if(list == null || list.size() == 0){
				hibernateTemplate.save(tag);
			}
		}
		hibernateTemplate.flush();
	}
	
	public Tags getTagByName(String name){
		Criteria criteria = session.createCriteria(Tags.class);
		criteria.add(Restrictions.eq("tagName", name));
		List<Tags> tags = criteria.list();
		if(tags != null && !tags.isEmpty()){
			return tags.get(0);
		}
		else
			return null;
	}
	
	public void saveActivityTags(ActivityTags tag){
		hibernateTemplate.save(tag);
	}
}
